package com.example.blog.controller;

import com.example.blog.model.BlogInfo;
import com.example.blog.model.Result;
import com.example.blog.model.UserInfo;
import com.example.blog.service.UserService;
import com.example.blog.utils.JWTUtils;
import com.example.blog.utils.SecurityUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RequestMapping("/user")
@RestController

public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    public Result selectByName(String username, String password){
        if(!StringUtils.hasLength(username)||!StringUtils.hasLength(password)){
            log.error("账户和密码不能为空");
            return Result.fail("用户和密码为空");

        }
        UserInfo userInfo=userService.selectByName(username);

        ;



         //判断账户和密码是否正确
        if(userInfo==null||!SecurityUtil.verify(password,userInfo.getPassword())){
            log.error("账号和密码错误");
            return Result.fail("账户和密码错误");

        }
        Map<String,Object> claims = new HashMap<>();
        claims.put("id",userInfo.getId());
        claims.put("username",userInfo.getUsername());
        String token = JWTUtils.genJwt(claims);
        log.info("生成的token:" + token);

        return Result.success(token);

    }

    @RequestMapping("/getUserInfo")
    public UserInfo getUserInfo(HttpServletRequest request){
        String jwtToken = request.getHeader("user_token");
        Integer userId = JWTUtils.getUserIdFromToken(jwtToken);
        Assert.notNull(userId,"userId不能为空");

        return userService.selectUserInfoById(userId);

    }
    @RequestMapping("/getAuthorInfo")
    public Result getAuthorInfo(Integer blogId){
        if (blogId==null && blogId<1){
            return Result.fail("博客ID不正确");
        }
        UserInfo userInfo = userService.getUserInfoByBlogId(blogId);
        return Result.success(userInfo);


    }


}
